/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-01-12 22:37:26
 */
// 新建js 以插件形式引入
import io, { Socket } from 'socket.io-client'
import * as IndexedDB from '@/indexedDB'
import { ChatRecord, ChatUnreadMessage } from '@/interface'
import { clone, equals, head, isEmpty } from 'ramda'
import { BasicDataModule } from '@/store/modules/basicData'
import { isTrue } from '../tools'
const userId = localStorage.getItem('userId')
export default {
	install: (app: any, { connection, options }: any) => {
		const socket = io(connection, options)
		app.config.globalProperties.$socket = socket
		app.provide('socket', socket)
		socket.emit('storeClientInfo', { userId })
		socket.emit('unread', userId)
		socket.emit('getFriendsNotice', { userId })
		socket.emit('messageNotice', { userId })
		monitorMessage(socket)
		monitorAcceptChat(socket)
		monitorUnread(socket)
		monitorFriendsAdd(socket)
		getContacts(socket)
	},
}
/** 监听消息 */
function monitorMessage(socket: Socket) {
	socket.on('message', (data: any[]) => {
		console.log(data, 'message')
	})
}
/** 接受聊天信息 */
function monitorAcceptChat(socket: Socket) {
	// 接受用户消息
	socket.on('acceptChat', acceptMessage)
	// 接受群聊消息
	socket.on('acceptGroupChatMessage', acceptMessage)
}
/** 监听未读消息 */
function monitorUnread(socket: Socket) {
	socket.on('unread', (data: { [key: number]: ChatUnreadMessage }) => {
		BasicDataModule.SET_CHATRECORD(data)
	})
}
/** 监听新朋友通知 */
function monitorFriendsAdd(socket: Socket) {
	socket.on('getFriendsNotice', (data: { [key: number]: number }) => {
		BasicDataModule.SET_FRIENDS(data)
		BasicDataModule.SET_UNREADFRIENDSTOTALCOUNT(data)
	})
}
/** 获取联系人 */
function getContacts(socket: Socket) {
	socket.on('getContacts', () => {
		BasicDataModule.getContacts()
	})
}
/** 接受消息 */
async function acceptMessage(data: ChatRecord) {
	const tableName = `user-chat-record-${isTrue(data.groupChat) ? data.group_id : data?.userId}`
	const userChatRecordReadAll = (await IndexedDB.readAll(tableName)) as ChatRecord[]
	const isHistorySessionSome = BasicDataModule.historySession.some((item) => {
		const historicalUserSessionsId = item.historicalUserSessionsId
		return isTrue(item.groupChat)
			? equals(historicalUserSessionsId, String(data.group_id))
			: equals(historicalUserSessionsId, String(data.userId))
	})
	if (!isHistorySessionSome) {
		const { success } = await API.blog.historySession.createHistorySession.request({
			userId,
			historicalUserSessionsId: isTrue(data.groupChat) ? data.group_id : data.userId,
		})
		if (success) {
			BasicDataModule.getHistorySession()
		}
	}
	if (!isEmpty(userChatRecordReadAll)) {
		// 删除indexedDB首条聊天记录并写入最新消息
		await IndexedDB.remove({
			tableName,
			key: head(userChatRecordReadAll)?.id as number,
		})
		IndexedDB.add<ChatRecord>(tableName, clone(data))
	}
}
